from flask import Flask
from flask import request
import json
import os
import uuid
import cv2
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
import tensorflow  as tf
from nets.test import app_predict
app = Flask(__name__)

model = tf.keras.models.load_model("model/cnn.h5")
# https://blog.csdn.net/qq_39089503/article/details/84578321

app = Flask(__name__)


def detect_faces(image_path):
    img = cv2.imread(image_path)  # ndarray
    # eye_cascade = cv2.CascadeClassifier("static/haarcascades/haarcascade_eye_tree_eyeglasses.xml")
    face_cascade = cv2.CascadeClassifier("static/haarcascades/haarcascade_frontalface_alt.xml")
    if img.ndim == 3:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 色彩空间的转换 BGR 2 GRAY
    else:
        gray = img  # 如果img维度为3，说明不是灰度图，先转化为灰度图gray，如果为2，原图就是灰度图
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=2, minSize=(30, 30),
                                          flags=cv2.CASCADE_SCALE_IMAGE)
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
    return len(faces), img


@app.route("/")
def index():
    return "Hello world"


resSets = {}


@app.route('/postdata', methods=['POST'])
def postdata():
    f = request.files['content']
    user_input = request.form.get("name")
    basepath = os.path.dirname(__file__)  # 当前文件所在路径
    src_imgname = str(uuid.uuid1()) + ".jpg"
    upload_path = os.path.join(basepath, 'static/srcImg/')
    if os.path.exists(upload_path) == False:
        os.makedirs(upload_path)
    f.save(upload_path + src_imgname)

    save_path = os.path.join(basepath, 'static/resImg/')
    if os.path.exists(save_path) == False:
        os.makedirs(save_path)

    # img = cv2.imread(upload_path + src_imgname, 1)
    # 图像处理、图像识别
    # num, img = detect_faces()
    label= app_predict(upload_path + src_imgname, model)
    save_imgname = str(uuid.uuid1()) + ".jpg"
    # cv2.imwrite(save_path + save_imgname)
    resSets["value"] = label
    resSets["resurl"] = "http://127.0.0.1:8090" + '/static/resImg/' + save_imgname
    return json.dumps(resSets, ensure_ascii=False)


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8090)
